package com.yxinmiracle.utils.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 功能描述
 *
 * @author: zyu
 * @description: APP登录Token的生成和解析
 * @date: 2019/3/30 15:14
 */
public class JwtUtil {

    /**
     * token秘钥，请勿泄露，请勿随便修改 backups:JKKLJOoadsafa
     */
    public static final String SECRET = "JKKLJOoadsafa";

    /**
     * token 过期时间: 10天
     */
    public static final int calendarField = Calendar.DATE;
    public static final int calendarInterval = 10;

    /**
     * JWT生成Token.<br/>
     * <p>
     * JWT构成: header, payload, signature
     *
     * @param user_id 登录成功后用户user_id, 参数user_id不可传空
     */
    public static String createToken(Integer user_id) throws Exception {
        Date iatDate = new Date();
        // expire time
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expiresDate = nowTime.getTime();

        // header Map
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        // build token
        // param backups {iss:Service, aud:APP}
        String token = JWT.create().withHeader(map) // header
                .withClaim("iss", "Service") // payload
                .withClaim("aud", "APP").withClaim("user_id", null == user_id ? null : user_id.toString())
                .withIssuedAt(iatDate) // sign time
                .withExpiresAt(expiresDate) // expire time
                .withSubject("pec-admin")
                .withIssuer("yxinmiracle")
                .sign(Algorithm.HMAC256(SECRET)); // signature

        return token;
    }


    /**
     * 解密Token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Map<String, Claim> verifyToken(String token) throws Exception{
        DecodedJWT jwt = null;
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        jwt = verifier.verify(token);
        return jwt.getClaims();
    }


    /**
     * 根据Token获取user_id
     *
     * @param token
     * @return user_id
     */
    public static Integer getAppUID(String token) throws Exception{
        Map<String, Claim> claims = verifyToken(token);
        Claim user_id_claim = claims.get("user_id");
        if (null == user_id_claim || StringUtils.isEmpty(user_id_claim.asString())) {
            // token 校验失败, 抛出Token验证非法异常
        }
        return Integer.valueOf(user_id_claim.asString());
    }

    public static void main(String[] args) {
        try {
            //eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJBUFAiLCJ1c2VyX2lkIjoiMSIsImlzcyI6IlNlcnZpY2UiLCJleHAiOjE2NDUzMjYyNTAsImlhdCI6MTY0NDQ2MjI1MH0.9VqEDG9QjAXxImzhgavfrkOvr73uBIbVJ9dzQcAMUQ0
            String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJBUFAiLCJzdWIiOiJwZWMtYWRtaW4iLCJ1c2VyX2lkIjoiMSIsImlzcyI6Inl4aW5taXJhY2xlIiwiZXhwIjoxNjQ1ODc5NjY3LCJpYXQiOjE2NDUwMTU2Njd9.Cc1dWO4uaEWrYmjo5cOfckEs6NGI4RoRlbZ9LZvkZik";
            Map<String, Claim> stringClaimMap = verifyToken(token);
            Integer appUID = getAppUID(token);
            System.out.println(appUID);
            Claim exp = stringClaimMap.get("exp");
            System.out.println(exp.asLong());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}